package org.itboys.shop.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.itboys.admin.entity.BusinessCenter;
import org.itboys.admin.service.BusinessCenterService;
import org.itboys.admin.service.BusinessCenterUserService;
import org.itboys.admin.tools.AdminCookieHolder;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.member.entity.Member;
import org.itboys.member.service.MemberService;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.mongodb.utils.query.AceUtils;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.itboys.pay.weixin.WeixinPaySignTool;
import org.itboys.product.constant.ProductConstant;
import org.itboys.product.entity.Product;
import org.itboys.product.service.ProductService;
import org.itboys.seller.constant.SellerConstants;
import org.itboys.seller.entity.Seller;
import org.itboys.seller.entity.SellerUser;
import org.itboys.seller.service.SellerService;
import org.itboys.seller.service.SellerUserService;
import org.itboys.shop.tools.WeixinUserInfoUtils;
import org.itboys.weixin.entity.WeixinConfig;
import org.itboys.weixin.service.WeixinConfigService;
import org.itboys.weixin.tools.HttpHelper;
import org.itboys.weixin.tools.SignTool;
import org.itboys.weixin.tools.WXUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.itboys.shop.WXConstants.appId;

/**
 * 微信授权相关
 *
 * @author weisky
 */
@RestController
@RequestMapping("/weixin")
public class WeixinController extends BaseController {

    @Autowired
    private WeixinConfigService weixinConfigService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private BusinessCenterService businessCenterService;
    @Autowired
    private ProductService productService;
    @Autowired
    private SellerService sellerService;

    @RequestMapping("/getWeixinConfigById")
    public void getWeixinConfigById(@RequestParam Long weixinId, HttpServletResponse response, HttpServletRequest request) {
        try {
            AjaxUtils.renderJson(response, weixinConfigService.getById(weixinId));
        } catch (Exception e) {
            logger.error("getWeixinConfigById error", e);
            AjaxUtils.renderJson(response, 0);
        }
    }

    @RequestMapping("/getMemberByOpenId")
    public void getMemberByOpenId(@RequestParam String openId, HttpServletResponse response, HttpServletRequest request) {
        try {
            List<Member> list = memberService.findByField("openId", openId);
            if (list != null && list.size() > 0) {
            	 logger.info("log---------------------:"+JSON.toJSONString(list.get(0)));
                request.getSession().setAttribute("user",list.get(0));
                AjaxUtils.renderJson(response, list.get(0));
            } else {
                AjaxUtils.renderJson(response, null);
            }
        } catch (Exception e) {
            logger.error("getMemberByOpenId error", e);
            AjaxUtils.renderJson(response, 0);
        }
    }

    /**
     * 在授权页，获取当前微信用户信息
     * @param appid
     * @param secret
     * @param grant_type
     * @param code
     * @param response
     * @param request
     */
    @RequestMapping("/getWxUserInfo")
    public void getWxUserInfo(String appid, String secret, String grant_type, String code,
                              HttpServletResponse response, HttpServletRequest request){
        String callbackName = request.getParameter("callback");
        String access_token = "";
        String openid = "";
        try{
            if (code == null){
                AjaxUtils.renderJsonporJson(response, callbackName, ResultPageDOHelper.getErrorResultDO(-2, "error! code is null!"), new String[0]);
            }

            Map<String, Object> param_1 = Maps.newHashMapWithExpectedSize(4);
            param_1.put("appid", appid);
            param_1.put("secret", secret);
            param_1.put("code", code);
            param_1.put("grant_type", grant_type);

            String result = HttpHelper.doGet("https://api.weixin.qq.com/sns/oauth2/access_token", param_1);
                    String errcode = String.valueOf(JSON.parseObject(result).get("errcode"));
            if (StringUtils.equals(errcode, "40029")){
                AjaxUtils.renderJsonporJson(response, callbackName, ResultPageDOHelper.getErrorResultDO(-3, "error! invalid code!"), new String[0]);
            }
            access_token = String.valueOf(JSON.parseObject(result).get("access_token"));
            //注意  网页授权页的access_token跟基础支持的access_token不同  所以不需要缓存
            openid = (String) JSON.parseObject(result).get("openid");

            Map<String, Object> param_2 = Maps.newHashMapWithExpectedSize(3);
            param_2.put("access_token", access_token);
            param_2.put("openid", openid);
            param_2.put("lang", "zh_CN");

            String result_2 = HttpHelper.doGet("https://api.weixin.qq.com/sns/userinfo", param_2);
                    AjaxUtils.renderJsonporJson(response, callbackName, ResultPageDOHelper.getMsgResultDO(result_2, "success!"), new String[0]);
        } catch (Exception e){
            this.logger.error("getShops error!", e);
            AjaxUtils.renderJsonporJson(response, callbackName, ResultPageDOHelper.getErrorResultDO(-1, "error!"), new String[0]);
        }
    }


    @RequestMapping("/member/save")
    public void save(@RequestParam String username, @RequestParam String nickname, @RequestParam String logo, @RequestParam String thirdType, @RequestParam String thirdObjId,
                     @RequestParam Long weixinId, @RequestParam String openId, @Param("sex")Integer sex, @Param("mobile") String mobile, @Param("recId")Long recId, HttpServletResponse response, HttpServletRequest request) {
        try {
            Member oldMember = memberService.getByField("openId", openId);
            if(oldMember == null) {
                Member member = new Member(username, nickname, mobile, thirdType, thirdObjId, weixinId, openId, recId, sex, logo);
                member.setRegTime(new Date());
                memberService.save(member);
                if(recId != null) {
                    Member recMember = memberService.getById(recId);
                    member.setType(recMember.getType());
                    member.setPath(recMember.getPath() + member.getId() +"/");
                    member.setLevel(recMember.getLevel() + 1);
                    member.setCenterId(recMember.getCenterId());
                    member.setSellerId(recMember.getSellerId());
                } else {
                    member.setType(4);
                    member.setLevel(1);
                    BusinessCenter center = businessCenterService.getByField("weixinId",weixinId);
                    if(center != null) {
                        Member mm = memberService.getById(center.getSelfMemberId());
                        member.setCenterId(center.getId());
                        member.setPath(mm.getPath() + member.getId() +"/");
                    }
                }
                member.setIsBuyer(1);
                memberService.update(member);
            }
        } catch (Exception e) {
            logger.error("/member/save error", e);
        }
    }

//    wx.ready(function(){
//        wx.onMenuShareTimeline({
//                title: "$!{product.title}", // 分享标题
//                link: '$!{webRoot}/weixin/auth?recId=$!{memberId}&view=1-$!{product.id}', // 分享链接
//                imgUrl: '$!{product.imageUrl}', // 分享图标
//                success: function () {
//            // 用户确认分享后执行的回调函数
//        },
//        cancel: function () {
//            // 用户取消分享后执行的回调函数
//        }
//        });
//
//        wx.onMenuShareAppMessage({
//                title: "$!{product.title}", // 分享标题
//                desc: "$!{product.subTitle}", // 分享描述
//                link: '$!{webRoot}/weixin/auth?recId=$!{memberId}&weixinId=$!{weixinId}&view=1-$!{product.id}', // 分享链接
//                imgUrl: '$!{product.imageUrl}', // 分享图标
//                type: '', // 分享类型,music、video或link，不填默认为link
//                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
//                success: function () {
//            // 用户确认分享后执行的回调函数
//        },
//        cancel: function () {
//            // 用户取消分享后执行的回调函数
//        }
//        });
//    })

    @RequestMapping("/auth")
    public void auth(HttpServletRequest request,  @RequestParam("view") String view,
                          @RequestParam(value = "recId", required = false)Long recId,
                          @Param("state") String state,
                          @Param("code") String code, HttpServletResponse response) throws Exception {
        try {
            String[] array = view.split("-");
            Long weixinId = Long.parseLong(array[1]);
            WeixinConfig config = weixinConfigService.getById(weixinId);
            String openid = (String) request.getSession().getAttribute("openid");
            String headimgurl = (String) request.getSession().getAttribute("headimgurl");
            if (StringUtils.isBlank(openid)) {
                String redirect_uri = "http://mwx.chinatoplady.cn/weixin/auth?recId="+recId+"&view=" + view ; // 回调地址
                if (state == null) { // 第一次请求可以拿到，后面几次都是微信回调，参数只有code和state
                    state = redirect_uri;
                }
                // 超过3次丢弃请求
                char flag_1 = state.charAt(state.length() - 1); // 数字
                char flag_2 = state.charAt(state.length() - 2); // '_'
                if (flag_2 == '_' && Character.isDigit(flag_1)) {
                    if (flag_1 > '3'){
//						response.sendRedirect(resourceHolder.getStringValue("adminRoot") + Constants.ERROR_URL);
                        return;
                    }
                    state = state.substring(0, state.length() - 1) + (char) (flag_1 + 1);
                } else {
                    state += "?degree=_1";// 第一次
                }
                redirect_uri = URLEncoder.encode(redirect_uri, "utf-8");
                String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + config.getAppId() + "&redirect_uri="
                        + redirect_uri + "&response_type=code&scope=snsapi_userinfo&state=" + state + "#wechat_redirect";
                String userStr = "";

                if (code == null || StringUtils.EMPTY.equals(code)) { // 第一次请求和code没拿到
                    response.sendRedirect(url);
                    return;
                } else {
                    userStr = WeixinUserInfoUtils.getUserInfo(config.getAppId(), config.getAppSecret(),
                            "authorization_code", code, url, response); // 获取电机用户的openid，这里用snsapi_base，只能得到openid
                    /*JSONObject json = new JSONObject(userStr);
                    openid = String.valueOf(json.get("openid"));
                    headimgurl = String.valueOf(json.get("headimgurl"));
                    Member member = memberService.getByField("openId", openid);
                    if(member == null){
                        member = new Member();
                        member.setUsername(String.valueOf(json.get("nickname")));
                        member.setNickname(String.valueOf(json.get("nickname")));
                        member.setLogo(String.valueOf(json.get("headimgurl")));
                        member.setThirdType("weixin");
                        member.setThirdObjId("0");
                        member.setSex((Integer)json.get("sex"));
                        member.setWeixinId(config.getId());
                        member.setOpenId(openid);
                        member.setRegTime(new Date());
                        memberService.save(member);
                        if(recId != 0) {
                            Member mm = memberService.getById(recId);
                            member.setType(mm.getType());
                            member.setSellerId(mm.getSellerId());
                            member.setCenterId(mm.getCenterId());
                            member.setLevel(mm.getLevel() + 1);
                            member.setRecId(recId);
                            member.setPath(mm.getPath() + member.getId() + "/");
                        } else {
                            if(array[0].equals("1")) {
                                BusinessCenter center = businessCenterService.getByField("weixinId", weixinId);
                                member.setType(4);
                                member.setCenterId(center.getId());
                                member.setPath(memberService.getById(center.getSelfMemberId()).getPath() + member.getId() + "/");
                            } else if(array[0].equals("2")) {
                                Seller seller = sellerService.getById(Long.parseLong(array[2]));
                                member.setType(3);
                                member.setCenterId(seller.getCenterId());
                                member.setSellerId(seller.getId());
                                member.setPath(memberService.getById(seller.getSelfMemberId()).getPath() + member.getId() + "/");
                            }
                            member.setLevel(1);
                        }
                        member.setIsBuyer(1);
                        memberService.update(member);
                    }*/
                   
                    //request.getSession().setAttribute("user", member);
                    request.getSession().setAttribute("openid", openid);
                    request.getSession().setAttribute("headimgurl", headimgurl);
                }
            } else {
                Member member = memberService.getByField("openId", openid);
                request.getSession().setAttribute("user", member);
            }
            if(StringUtils.isBlank(view)){
                response.sendRedirect("http://mwx.chinatoplady.cn/weixin/product/index");
            } else {
                if(array[0].equals("1")){
                    response.sendRedirect("http://mwx.chinatoplady.cn/wx/product/detail?proId="+array[2]);
                } else if(array[0].equals("2")) {
                    response.sendRedirect("http://mwx.chinatoplady.cn/wx/shop/shopDetail?shopId="+array[2]);
                }
            }
            return;
        } catch (Exception e) {
            logger.error("/wx/health/member/getMember error", e);
//			response.sendRedirect(resourceHolder.getStringValue("adminRoot") + Constants.ERROR_URL);
            return;
        }
    }

    /**
     * 微信js签名
     * */
    @RequestMapping("/sign")
    public void sign(@RequestParam String url,@RequestParam Long weixinId,HttpServletResponse response, HttpServletRequest request) {
        try {
            WeixinConfig config = weixinConfigService.getById(weixinId);
            SignTool signTool = new SignTool(config.getAppId());
            String sign = WXUtils.checkSignature(signTool.getTimestamp(), signTool.getNoncestr(), url, config.getAppId(), config.getAppSecret());
            signTool.setSign(sign);
            AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(signTool, "success"));
        } catch (Exception e) {
            AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "error"));
        }
    }

}
